#
DL='https://s3.jcloud.sjtu.edu.cn/899a892efef34b1b944a19981040f55b-oss01/github-release/PowerShell/PowerShell/releases/download/v7.4.5/powershell-7.4.5-linux-musl-x64.tar.gz'
MIRROR='https://github.com/PowerShell/PowerShell/releases/download/v7.4.5/powershell-7.4.5-linux-musl-x64.tar.gz'

if grep -iEq 'alpine' /etc/issue || grep -iEq 'alpine' /etc/*-release
then
  echo 'linux is alpine'
  if [ -h /usr/bin/pwsh ]
  then
    echo 'powershell installed on alpine'
    if grep -Eq 'powershell' /etc/ssh/sshd_config
    then
      echo 'powershell_sshd_good'
      exit 0
    else
      echo '' >>  /etc/ssh/sshd_config
      echo 'Subsystem powershell /usr/bin/pwsh -sshs -NoLogo -NoProfile' >>  /etc/ssh/sshd_config
      echo 'UseDNS no' >>  /etc/ssh/sshd_config
      echo 'PermitRootLogin yes' >>  /etc/ssh/sshd_config
      rc-service sshd restart
      echo 'powershell_sshd_fixed'
      exit 0
    fi
  else
    echo 'installing powershell now'
    apk update
    apk add --no-cache \
    ca-certificates \
    less \
    ncurses-terminfo-base \
    krb5-libs \
    libgcc \
    libintl \
    libssl3 \
    libstdc++ \
    tzdata \
    userspace-rcu \
    zlib \
    icu-libs \
    curl \
    lttng-ust \
    wget

    cd /tmp
    mkdir  -p /opt/microsoft/powershell/7


    for i in `seq 1 6`
    do
      rm -rf /tmp/powershell*.tar.gz
      wget $DL
      if [ $? -eq 0 ]
      then
        DOWNLOAD_END=1
        break
      else
        wget $MIRROR
        if [ $? -eq 0 ]
        then
          DOWNLOAD_END=1
          break
        else
          echo '下载pwsh失败！'
          sleep 3
        fi
      fi
    done

    if ((DOWNLOAD_END=1))
    then
      echo '下载pwsh成功！'
    else
      echo '多次下载pwsh失败！脚本退出！'
      exit 2
    fi

    DDDD=`find /tmp -iname 'powershell*.tar.gz'`
    echo $DDDD
    tar -C /opt/microsoft/powershell/7 -xf ${DDDD}

    if [ -x /opt/microsoft/powershell/7/pwsh ]
    then
      ln -s /opt/microsoft/powershell/7/pwsh /usr/bin/pwsh
    else
      echo '安装pwsh失败！脚本退出！'
      exit 4
    fi

    if grep -Eq 'powershell' /etc/ssh/sshd_config
    then
      echo 'powershell_sshd_good'
      exit 0
    else
      echo '' >>  /etc/ssh/sshd_config
      echo 'Subsystem powershell /usr/bin/pwsh -sshs -NoLogo -NoProfile' >>  /etc/ssh/sshd_config
      echo 'UseDNS no' >>  /etc/ssh/sshd_config
      echo 'PermitRootLogin yes' >>  /etc/ssh/sshd_config
      rc-service sshd restart
      echo 'powershell_sshd_fixed'
      exit 0
    fi

  fi
else
  echo 'linux not alpine'
  exit 3
fi
